
<script src="/wang-editor/index.js"></script>
<script>
    var html ;//设置一个变量
    const {
        createEditor,
        createToolbar
    } = window.wangEditor
    //编辑器配置
    const editorConfig = {
        MENU_CONF: {},
        withCredentials:true,//定义该属性为ture表示允许跨域访问
        autofocus: true,
        scroll: true,
        maxLength: 1200,
        minLength: 200,
        placeholder: '请输入文本内容', //默认文字
        onChange(editor) {//当编辑器中发生改变时，获取最新html代码输出
            html = editor.getHtml()//获取HTML内容，editor.getText()是获取纯文本内容
            console.log('editor content', html)
            //将html的值赋值给id为neirong的文本框这里只是为了传值，保存到数据库
            document.getElementById('editor-container').value = html;
            // // 也可以同步到 <textarea>
        }
    }
    editorConfig.MENU_CONF['uploadImage'] = {
        // 上传图片的配置
        server: '/upload/file',//连接到接口文件，执行数据上传功能
        fieldName: 'file',
        maxFileSize: 6 * 1024 * 1024,
        maxNumberOfFiles: 200,
    }
    //创建编辑器
    const editor = createEditor({
        selector: '#editor-container',
        html: document.getElementById('neirong').innerText,
        config: editorConfig,
        mode: 'simple', // or 'simple'
    })
    //工具栏配置
    const toolbarConfig = {}
    //隐藏视频上传功能
    toolbarConfig.excludeKeys = [
        'group-video'
    ]
    //创建工具栏
    const toolbar = createToolbar({
        editor,
        selector: '#toolbar-container',
        config: toolbarConfig,
        mode: 'simple', // or 'simple'
    })
</script>
<script>
    //准备视图对象
    window.viewObj = {
        //初始化数据
        tbData: [],
    };

    layui.use(['jquery','table','upload','layer','element','form','laydate'],function () {
        var $ = layui.$, table = layui.table, form = layui.form,
            layer = layui.layer, laydate = layui.laydate,upload = layui.upload;
        laydate.render({elem:'#miaosha_start',type:'datetime',format:"yyyy-MM-dd HH:mm:ss"});
        laydate.render({elem:'#miaosha_end',type:'datetime'});
        laydate.render({elem:"#hexiao_end",type:"datetime"});

        //缩略图片上传
        $(".uploadPic").each(function (index,elem) {
            upload.render({
                elem: $(elem)
                ,url: '{{ route("admin.upload.file") }}'
                ,multiple: false
                ,data:{"_token":"{{ csrf_token() }}"}
                ,done: function(res){
                    if(res.errno == 0){
                        layer.msg(res.msg,{icon:1},function () {
                            $(elem).parent('.layui-upload').find('.layui-upload-box').html('<li><img src="'+res.data.url+'" /><p>上传成功</p></li>');
                            $(elem).parent('.layui-upload').find('.layui-upload-input').val(res.data.url);
                        })
                    }else {//如果上传失败
                        layer.msg(res.msg,{icon:2})
                    }
                }
            });
        });

        //轮播图上传
        $("#imagesUpload").each(function (index,elem) {
            upload.render({
                elem: $(elem)
                ,url: '{{ route("admin.upload.file") }}'
                ,multiple: true
                ,data:{"_token":"{{ csrf_token() }}"}
                ,done: function(res){
                    //上传完毕
                    if(res.errno == 0) {
                        layer.msg(res.msg,{icon:1},function () {
                            var li = '<li><a href="javascript:;" class="delete-images" title="删除">x</a><img src="'+res.data.url+'" /><p>上传成功</p><input type="hidden" name="images[]" value="' + res.data.url + '" /></li>';
                            $(elem).parent('.layui-upload').find('.layui-upload-list').append(li);
                        })
                    }else {
                        layer.msg(res.msg,{icon:2});
                    }
                }
            });
        });

        //删除已经上传的轮播图
        $("body").on('click','.delete-images',function () {
            $(this).parent().remove();
        });

        //详情图上传
        $("#uploadDetail").each(function (index,elem) {
            upload.render({
                elem: $(elem)
                ,url: '{{ route("admin.upload.file") }}'
                ,multiple: true
                ,data:{"_token":"{{ csrf_token() }}"}
                ,done: function(res){
                    //上传完毕
                    if(res.errno == 0) {
                        layer.msg(res.msg,{icon:1},function () {
                            var li = '<li><a href="javascript:;" class="delete-images" title="删除">x</a><img src="'+res.data.url+'" /><p>上传成功</p><input type="hidden" name="detail_images[]" value="' + res.data.url + '" /></li>';
                            $(elem).parent('.layui-upload').find('.layui-upload-list').append(li);
                        })
                    }else {
                        layer.msg(res.msg,{icon:2});
                    }
                }
            });
        });

        //todo  整理成通用
        var HtmlUtil = {
            /*1.用浏览器内部转换器实现html转码*/
            htmlEncode:function (html){
                //1.首先动态创建一个容器标签元素，如DIV
                var temp = document.createElement ("div");
                //2.然后将要转换的字符串设置为这个元素的innerText(ie支持)或者textContent(旧版火狐，google支持)
                (temp.textContent != undefined ) ? (temp.textContent = html) : (temp.innerText = html);
                //3.最后返回这个元素的innerHTML，即得到经过HTML编码转换的字符串了
                var output = temp.innerHTML;
                temp = null;
                return output;
            },
            /*2.用浏览器内部转换器实现html解码*/
            htmlDecode:function (text){
                //1.首先动态创建一个容器标签元素，如DIV
                var temp = document.createElement("div");
                //2.然后将要转换的字符串设置为这个元素的innerHTML(ie，火狐，google都支持)
                temp.innerHTML = text;
                //3.最后返回这个元素的innerText(ie支持)或者textContent(火狐，google支持)，即得到经过HTML解码的字符串了。
                var output = temp.innerText || temp.textContent;
                temp = null;
                return output;
            },
            /*3.用正则表达式实现html转码*/
            htmlEncodeByRegExp:function (str){
                var s = "";
                if(str.length == 0) return "";
                s = str.replace(/&/g,"&amp;");
                s = s.replace(/</g,"&lt;");
                s = s.replace(/>/g,"&gt;");
                s = s.replace(/\s/g,"&nbsp;");
                s = s.replace(/\'/g,"&#39;");
                s = s.replace(/\"/g,"&quot;");
                return s;
            },
            /*4.用正则表达式实现html解码*/
            htmlDecodeByRegExp:function (str){
                var s = "";
                if(str.length == 0) return "";
                s = str.replace(/&amp;/g,"&");
                s = s.replace(/&lt;/g,"<");
                s = s.replace(/&gt;/g,">");
                s = s.replace(/&nbsp;/g," ");
                s = s.replace(/&#39;/g,"\'");
                s = s.replace(/&quot;/g,"\"");
                return s;
            }
        };

        //产品编辑时初始化规格型号信息
        var skusString = '{{ $product->skus ?? '' }}', skusObj;
        if(skusString) {
            skusString = HtmlUtil.htmlDecode(skusString);
            skusObj = JSON.parse(skusString)

            viewObj.tbData = skusObj
        }

        //console.log(skusObj);

        //数据表格实例化
        var tbWidth = $("#tableRes").width();
        var layTableId = "layTable";
        var tableIns = table.render({
            elem: '#dataTable',
            id: layTableId,
            data: viewObj.tbData,
            width: tbWidth,
            page: false,
            loading: true,
            even: false, //不开启隔行背景
            cols: [[
                {title: '序号', type: 'numbers'},
                {field: 'title', type: "string", title: '规格型号',edit:"text"},
                {field: 'origin_price', type: "float", title: '原价',edit:"text"},
                {field: 'sold_price', type: "float", title: '售价',edit:"text"},
                {field: 'stock', title: '库存',edit:"text"},
                {field: 'id', title: '操作', templet: function(d){
                        return '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del" lay-id="'+ d.id +'"><i class="layui-icon layui-icon-delete"></i>移除</a>';
                    }}
            ]],
            done: function (res, curr, count) {
                viewObj.tbData = res.data;
            }
        });

        //定义事件集合
        var active = {
            addRow: function(){	//添加一行
                var oldData = table.cache[layTableId];
                var newRow = {id: new Date().valueOf(), title: '', origin_price:'',sold_price:'',stock:''};
                oldData.push(newRow);

                tableIns.reload({
                    data : oldData
                });
            },
            updateRow: function(obj){
                var oldData = table.cache[layTableId];
                for(var i=0, row; i < oldData.length; i++){
                    row = oldData[i];
                    if(row.id == obj.id){
                        $.extend(oldData[i], obj);
                        return;
                    }
                }
                tableIns.reload({
                    data : oldData
                });
            },
            removeEmptyTableCache: function(){
                var oldData = table.cache[layTableId];
                for(var i=0, row; i < oldData.length; i++){
                    row = oldData[i];
                    if(!row || !row.id){
                        oldData.splice(i, 1);    //删除一项
                    }
                    continue;
                }
                tableIns.reload({
                    data : oldData
                });
            },
        }

        //激活事件
        var activeByType = function (type, arg) {
            if(arguments.length === 2){
                active[type] ? active[type].call(this, arg) : '';
            }else{
                active[type] ? active[type].call(this) : '';
            }
        }

        //注册按钮事件
        $('.layui-btn[data-type]').on('click', function () {
            var type = $(this).data('type');
            activeByType(type);
        });

        //监听工具条
        table.on('tool(dataTable)', function (obj) {
            var data = obj.data, event = obj.event, tr = obj.tr; //获得当前行 tr 的DOM对象;
            switch(event){
                case "del":
                    layer.confirm('确定删除该行吗？', function(index){
                        obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                        layer.close(index);
                        activeByType('removeEmptyTableCache');
                    });
                    break;
            }
        });

        form.on('submit(productC)',function (data) {
            console.log(data)
            //var json = data.field;
            var loading = layer.load(2);
            //skus数据
            var oldData = table.cache[layTableId];
            var formData = $("#product").serializeArray();
            var postData = {};//声明一个对象
            $.each(formData,function(index,field){
                //通过变量，将属性值，属性一起放到对象中。只取有值的name
                if(field.value != null) {
                    postData[field.name] = field.value;
                }
            });

            //添加规格型号信息
            postData['skus'] = oldData;
            postData['detail'] = editor.getHtml()
            console.log('postData:');
            console.log(postData);

            $.ajax({
                url : "{{ isset($product->id) ? route('product.update',$product->id) : route('product.store') }}",
                data : postData,
                dataType : "json",
                type : "{{ isset($product->id) ? 'PUT' : 'POST' }}",
                success : function (res) {
                    layer.closeAll('loading');

                    if(res.code == 0) {
                        //layer.msg(res.message)
                        layer.msg(res.message,{icon:1,time:2000},function () {
                            window.location.href = "{{ route('product.index') }}"
                        });
                    }else if(res.code == 422){//表单验证失败，返回所有的错误信息
                        //todo  优化成可视化更好的html元素，最好是table表格，或者在相应的表单元素下面以小号红字提醒。
                        let errorHtml = '';
                        $.each(res.errors,function (name,value) {
                            $.each(value,function (index,item) {
                                errorHtml += item + "<br/ >";
                            })
                        });
                        layer.open({
                            type: 0,
                            title: '数据有误',
                            closeBtn: false,
                            btnAlign: "c",
                            icon: 2,
                            area: '400px',
                            content: errorHtml
                        });
                    }else {
                        layer.msg(res.message,{icon:2});
                    }
                },
                error : function (err) {
                    layer.closeAll('loading');
                    layer.msg(err.message,{icon:2});
                },
            })
        })
        //栏目联动
        form.on('select(parent_id)',function (data) {
            let parent_id = data.value;
            if(parent_id != "") {
                $.ajax({
                    url : "{{ route('admin.category.data') }}",
                    data : {parent_id:parent_id},
                    dataType : "json",
                    type : "GET",
                    success : function (res) {
                        if(res.code == 0) {
                            $("#category_id").html('');
                            let categories = res.data;
                            for(let i=0;i<categories.length;i++) {
                                $("#category_id").append('<option value="' + categories[i]['id'] +'">' + categories[i]['name'] + '</option>');
                            }
                            form.render('select');
                        }else {
                            layer.msg(res.message,{icon:2});
                        }
                    },
                    error : function (err) {
                        layer.msg(err.message,{icon:2});
                    },
                })
            }else {
                $("#category_id").html('');
                form.render('select');
            }
        })
    })
</script>



